import { readonly, shallowRef } from 'vue'
import { useLocalStorage } from '@vueuse/core'
import { defineStore } from 'pinia'
import { useCreatorStore } from '@/store/creator'
import { $t } from '@/i18n'
import { LOCAL_STORAGE_KEYS } from '@/constant'

const ONE_DAY_MS = 24 * 60 * 60 * 1000

export const useSubscribeTipStore = defineStore('subscribe-tip', () => {
  const { getCreator } = useCreatorStore()
  const millisTable = useLocalStorage(LOCAL_STORAGE_KEYS.CARE_ME_MORE_TIP, {})

  let clearTimerId
  const subscribeTip = shallowRef(null)

  async function trigger(aff) {
    const creator = await getCreator(aff)
    const needTip = !millisTable.value[aff] || Date.now() - millisTable.value[aff] > ONE_DAY_MS
    if (!creator.is_subscribe && needTip) {
      millisTable.value[aff] = Date.now()
      subscribeTip.value = { aff, msg: $t(`info.careMeMore${Math.floor(Math.random() * 5) + 1}`) }
      clearTimerId = setTimeout(clear, 5000)
    }
  }

  function clear() {
    subscribeTip.value = null
    clearTimeout(clearTimerId)
  }

  return {
    subscribeTip: readonly(subscribeTip),
    trigger,
    clear,
  }
})
